package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user,HttpSession session){
        log.info("登录用户信息：{}",user);

        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)){
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);

            //调用阿里云提供的段in服务API完成发送短信
//            SMSUtils.sendMessage("吉瑞外卖","",phone,code);

            //需要将生成的验证码保存到Session
            session.setAttribute(phone,code);
            return R.success("手机验证码短信发送成功");
        }
        return R.success("短信发送失败");
    }

    @PostMapping("/login")
    public R<String> login(@RequestBody Map map,HttpSession session){
        log.info("当前登录用户信息：{}",map);
        //获取用户输入的手机号
        String phone = (String) map.get("phone");
        //获取验证码
        String code = (String) map.get("code");
        //获取存在session中的验证码
        Object codeInSession = session.getAttribute(phone);

        //比较验证码
        if(codeInSession != null && codeInSession.equals(code)){

            //构造条件构造器
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);

            //查到的user如果为空，则说明该用户是新用户，自动完成注册
            if(user == null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);

                //设置一个名字，方便订单管理页面进行展示
                user.setName("小王"+phone.substring(0,3));

                userService.save(user);
            }

            //登录成功的话，就将用户id存入session中，并返回登录成功的结果
            session.setAttribute("user",user.getId());

            return R.success("登录成功");
        }

        return R.error("登录失败");
    }

    /**
     * 用户退出
     *
     * @param request
     * @return
     */
    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request) {
        //清理Session中保存的当前登录用户的id
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }

}